<?php
namespace app\controller;

use app\BaseController;
use think\facade\View;
use think\facade\Request;
use SimpleXMLElement;
use ImgCompress;
class Tu extends BaseController
{
    public function index()
    {
        // echo 'hello';
        return View::fetch('tu/index');
    }


    public function uploadImg(){
        $file = $_FILES["file"];
        $param=Request::param();
        $value=$param['value'];
        // $value = $_GET['value'];
        $arr=explode('.',$file['name']);
        $type=array_pop($arr);
        //创建文件夹获取当前年月日
        $folder="/upload/images/".date('Y-m-d');
        if(!is_dir('.'.$folder)){
            mkdir('.'.$folder,0777);//创建年+月的文件夹权限为最高
        }
        $imgurl=$folder.'/'.$this->GetRandStr(6).'.'.$type;
        $result = $this->compressImage($file['tmp_name'], $imgurl, $value);

        return json(['code'=>200,'url'=>$result,'value'=>$value]);
        // echo "压缩后的图片路径：" . $result;
    }

    public function compressImage($source, $destination, $quality) {
        $info = getimagesize($source);
        $destination1=".".$destination;
        if ($info['mime'] == 'image/jpeg') {
            $image = imagecreatefromjpeg($source);
        } elseif ($info['mime'] == 'image/gif') {
            $image = imagecreatefromgif($source);
        } elseif ($info['mime'] == 'image/png') {
            $image = imagecreatefrompng($source);
        }
     
        imagejpeg($image, $destination1, $quality);
        imagedestroy($image);
        return $destination;
    }
     
    // $result = compressImage('input.jpg', 'output.jpg', 80);
    // echo "压缩后的图片路径：" . $result;
    //生成随机订单号
    public function GetRandStr($length){
        $str = 'abcdefghijklmnopqrstuvwxyz0123456789';
        $len = strlen($str)-1;
        $randstr = '';
        for ($i=0;$i<$length;$i++) {
            $num=mt_rand(0,$len);
            $randstr .= $str[$num];
        }
        return $randstr;
    }




    
}
